package com.ys.otms.services;

import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import com.ys.otms.dao.IUserDao;
import com.ys.otms.dto.GzhInfoDto;
import com.ys.otms.utils.DateUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxServices {

    private static final String APP_ID = "wx58519e3ec84a9952";

    private static final String APP_SECRET = "e93747b9259a61c7c3b12ae9ca235da6";

    private static Logger logger = LoggerFactory.getLogger(WxServices.class);

    @Autowired
    private IUserDao iUserDao;

    @Scheduled(fixedDelay = 3600 * 12 * 1000)
    //12小时执行一次
    public void getFollows() {
        logger.info("WxServices getFollows start date:{}", DateUtil.getStandardNowTime());
        setDefaultData();
        ApiResult apiResult = UserApi.getFollows();
        String json = apiResult.getJson();
        JSONObject jsonObject = JSONObject.fromObject(json);
        JSONObject dataObj = (JSONObject) jsonObject.get("data");
        if (null != dataObj) {
            JSONArray jsonArray = dataObj.getJSONArray("openid");
            List<String> openIdList = new ArrayList<>();
            //先清空，在添加，不然数据少了，以前的数据还在
            logger.info("WxServices getFollows deleteAllGzhList 1:{}");
            iUserDao.deleteAllGzhList();
            logger.info("WxServices getFollows deleteAllGzhList 2:{}");
            int length = jsonArray.size();
            if (length > 100) {
                for(int i = 0; i < length; i++) {

                    if (i%100 == 0 && i != 0) {
                        logger.info("WxServices getFollows start i:{}",i);
                        ApiResult apiResult1 = batchGetUserInfo(openIdList);
                        insertGzhList(apiResult1);
                        openIdList = new ArrayList<>();
                    }
                    openIdList.add((String) jsonArray.get(i));
                }
                if (openIdList.size() > 0) {
                    ApiResult apiResult1 = batchGetUserInfo(openIdList);
                    insertGzhList(apiResult1);
                }
            }
            else {
                logger.info("WxServices getFollows start:{}", openIdList);
                ApiResult apiResult1 = batchGetUserInfo(openIdList) ;
                insertGzhList(apiResult1);
            }
        }
    }

    public ApiResult getFollows1() {
        setDefaultData();
        ApiResult apiResult = UserApi.getFollows();
        return apiResult;
    }

    private static void setDefaultData() {
        ApiConfig apiConfig = new ApiConfig();
        apiConfig.setAppId(APP_ID);
        apiConfig.setAppSecret(APP_SECRET);
        ApiConfigKit.setThreadLocalApiConfig(apiConfig);
    }

    private static ApiResult batchGetUserInfo(List<String> openIdList) {
        Map<String, List<Map<String, Object>>> userListMap = new HashMap<>();

        List<Map<String, Object>> userList = new ArrayList<>();
        for (String openId : openIdList) {
            Map<String, Object> mapData = new HashMap<>();
            mapData.put("openid", openId);
            mapData.put("lang", "zh-CN");
            userList.add(mapData);
        }
        userListMap.put("user_list", userList);

        return UserApi.batchGetUserInfo(JsonUtils.toJson(userListMap));
    }


    private void insertGzhList(ApiResult apiResult) {
        logger.info("WxServices insertGzhList start date:{}", DateUtil.getStandardNowTime());
        String json = apiResult.getJson();
        JSONObject jsonObject = JSONObject.fromObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray("user_info_list");
        List<GzhInfoDto> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
            String openId = jsonObject1.getString("openid");
            String unionId = jsonObject1.getString("unionid");
            String nickName = jsonObject1.getString("nickname");
            //nickName中有表情，插入要修改好多mysql的配置，先不准备插入
            GzhInfoDto gzhInfoDto = new GzhInfoDto(openId, unionId, nickName);
            list.add(gzhInfoDto);
        }

        iUserDao.insertGzhList(list);
    }
}
